<!DOCTYPE html>
<html lang="zh-Hans">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Pointer in Python | LYH&#39;s Blog</title>

    
<link href="/favicon.ico" rel="shortcut icon" type="image/x-icon" />




<meta name="author" content="Erwin" />
<meta name="description" content="Simulating pointer in python.
" />



<meta name="generator" content="Hugo 0.92.2" />

<link rel="canonical" href="http://erwinliyh.github.io/posts/python_pointer/" />


<meta property="og:title" content="Pointer in Python" />
<meta property="og:description" content="Simulating pointer in python." />
<meta property="og:type" content="article" />
<meta property="og:url" content="http://erwinliyh.github.io/posts/python_pointer/" /><meta property="og:image" content="http://erwinliyh.github.io"/><meta property="article:section" content="posts" />
<meta property="article:published_time" content="2021-08-24T14:49:09+08:00" />
<meta property="article:modified_time" content="2021-08-24T14:49:09+08:00" />




<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="http://erwinliyh.github.io"/>

<meta name="twitter:title" content="Pointer in Python"/>
<meta name="twitter:description" content="Simulating pointer in python."/>


<link rel="stylesheet" href="/css/semantic.min.css" />
<link rel="stylesheet" href="/css/icomoon.css" />
<link rel="stylesheet" href="/css/OverlayScrollbars.min.css" />
<link rel="stylesheet" href="/css/github-markdown.css" />
<link rel="stylesheet" href="/css/site.css" />

<style>
  a:not(.ui.button):hover {
    text-decoration: underline;
  }

  
  a:not(.ui.button) {
    color: seagreen !important;
  }
  

  
  .inverted a:not(.ui.button),
  .inverted a:not(.ui.button):hover {
     color: darkseagreen !important;
  }
  

  
  body.default {
    
    background-color: #f2cac9;
    

    
    background-image: url(/img/1.jpg);
    
  }
  

  
  body.dark {
    
    background-color: #b36d61;
    

    
    background-image: url(/img/1.jpg);
    
  }
  
</style>


    



<link rel="stylesheet" data-highlight href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release/build/styles/github.min.css" />







    
    <link rel="stylesheet" href="/css/background.css" />
    
  </head>

  <body class="default">
    
<nav class="ui secondary menu dream-menu">

  <div class="item">
    <i class="large link bullseye icon dream-flip-toggle" title="Flip it!"></i>
  </div>
  <div class="item">
    <i class="large link home icon" title="Home" onclick="window.location.href = 'http:\/\/erwinliyh.github.io'"></i>
  </div>
  <div class="item">
    <i class="large link icon theme-switch" onclick="themeSwitch()"></i>
  </div>
  
  <div class="item">
    <i class="large link search icon" onclick="toggleSearch()"></i>
  </div>
  
</nav>

    <div class="flip-container">
      <div class="flipper">
        <section class="front">
          <div class="dream-max-width">
            
<div class="ui relaxed grid dream-grid">
  <aside class="sixteen wide mobile sixteen wide tablet four wide computer column dream-single-aside">
    
    
    <div class="ui segment toc">
      <nav id="TableOfContents">
  <ul>
    <li><a href="#mutable-and-immutable-value-in-memory">Mutable and immutable value in memory</a></li>
    <li><a href="#using-mutable-value-simulate-pointer">Using mutable value simulate pointer</a></li>
  </ul>
</nav>
    </div>
    
    <div class="ui segment actions">
      <button
        class="ui circular icon button save-as-image"
        title="Save as image"
        onclick="savePostAsImg()">
        <i class="save icon"></i>
      </button>

      <a href="https://twitter.com/intent/tweet?text=Pointer%20in%20Python&url=http%3a%2f%2ferwinliyh.github.io%2fposts%2fpython_pointer%2f" class="ui circular twitter icon button">
  <i class="twitter icon"></i>
</a>
<a href="https://facebook.com/sharer/sharer.php?u=http%3a%2f%2ferwinliyh.github.io%2fposts%2fpython_pointer%2f" class="ui circular facebook icon button">
  <i class="facebook icon"></i>
</a>

    </div>
  </aside>
  <div class="sixteen wide mobile sixteen wide tablet twelve wide computer column markdown-body dream-single" id="dream-save-post-as-img">
    
    <section class="ui attached segment">
      <header>
        <h1 class="ui large header">Pointer in Python<div class="sub header">
            @
            
              
                Erwin
              
            

            | 
                Tuesday, Aug 24, 2021
              

            | 2 minutes read

            | Update at
              
                Tuesday, Aug 24, 2021
              
          </div>
        </h1>
      </header>

      <article class="main"><p>Simulating pointer in python.</p>
<h2 id="mutable-and-immutable-value-in-memory">Mutable and immutable value in memory</h2>
<p>For immutable value like integer, consider the code below:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python">a <span style="color:#f92672">=</span> <span style="color:#ae81ff">10</span>
b <span style="color:#f92672">=</span> a
b <span style="color:#f92672">=</span> <span style="color:#ae81ff">20</span>
</code></pre></div><p>After that, a will equal to 10 and b will equal to 20. The pictures demonstrate the memory behind the code:</p>
<p><img src="/img/202108241508.svg" alt=""></p>
<p>We  can find the name of the value is actually a pointer, but we can&rsquo;t use them in immutable value, because we can&rsquo;t change the value pointed.</p>
<p>For mutable value like list, consider the code below:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python">a <span style="color:#f92672">=</span> [<span style="color:#ae81ff">1</span>,<span style="color:#ae81ff">2</span>,<span style="color:#ae81ff">3</span>,<span style="color:#ae81ff">4</span>]
b <span style="color:#f92672">=</span> a
b<span style="color:#f92672">.</span>append(<span style="color:#ae81ff">5</span>)
</code></pre></div><p>After that, both a and b will be [1,2,3,4,5], the memory usage is like:</p>
<p><img src="/img/202108241532.svg" alt=""></p>
<p>By this property in mutable value, we can simulate pointer like c++.</p>
<h2 id="using-mutable-value-simulate-pointer">Using mutable value simulate pointer</h2>
<p>Take linked list by python as an example. This is the second question in LeetCode, Add two numbers.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">ListNode</span>:
    <span style="color:#66d9ef">def</span> __init__(self, val<span style="color:#f92672">=</span><span style="color:#ae81ff">0</span>, next<span style="color:#f92672">=</span><span style="color:#66d9ef">None</span>):
        self<span style="color:#f92672">.</span>val <span style="color:#f92672">=</span> val
        self<span style="color:#f92672">.</span>next <span style="color:#f92672">=</span> next
</code></pre></div><div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Solution</span>:
    <span style="color:#66d9ef">def</span> <span style="color:#a6e22e">addTwoNumbers</span>(self, l1: ListNode, l2: ListNode) <span style="color:#f92672">-&gt;</span> ListNode:
        head <span style="color:#f92672">=</span> ListNode()
        p1 <span style="color:#f92672">=</span> head
        p2 <span style="color:#f92672">=</span> (l1,l2)
        d <span style="color:#f92672">=</span> <span style="color:#ae81ff">0</span>
        <span style="color:#66d9ef">while</span> <span style="color:#66d9ef">True</span>:
            <span style="color:#66d9ef">if</span> p2[<span style="color:#ae81ff">0</span>] <span style="color:#f92672">and</span> p2[<span style="color:#ae81ff">1</span>]:
                value, s <span style="color:#f92672">=</span> ((p2[<span style="color:#ae81ff">0</span>]<span style="color:#f92672">.</span>val <span style="color:#f92672">+</span> p2[<span style="color:#ae81ff">1</span>]<span style="color:#f92672">.</span>val <span style="color:#f92672">+</span> d)<span style="color:#f92672">%</span><span style="color:#ae81ff">10</span>),((p2[<span style="color:#ae81ff">0</span>]<span style="color:#f92672">.</span>val <span style="color:#f92672">+</span> p2[<span style="color:#ae81ff">1</span>]<span style="color:#f92672">.</span>val <span style="color:#f92672">+</span> d)<span style="color:#f92672">//</span><span style="color:#ae81ff">10</span>)
                p1<span style="color:#f92672">.</span>next <span style="color:#f92672">=</span> ListNode(value)
                p1 <span style="color:#f92672">=</span> p1<span style="color:#f92672">.</span>next
                p2 <span style="color:#f92672">=</span> (p2[<span style="color:#ae81ff">0</span>]<span style="color:#f92672">.</span>next,p2[<span style="color:#ae81ff">1</span>]<span style="color:#f92672">.</span>next)
                d <span style="color:#f92672">=</span> s
            <span style="color:#66d9ef">elif</span> p2[<span style="color:#ae81ff">0</span>]<span style="color:#f92672">==</span><span style="color:#66d9ef">None</span> <span style="color:#f92672">and</span> p2[<span style="color:#ae81ff">1</span>]<span style="color:#f92672">!=</span><span style="color:#66d9ef">None</span>:
                value, s <span style="color:#f92672">=</span> ((p2[<span style="color:#ae81ff">1</span>]<span style="color:#f92672">.</span>val <span style="color:#f92672">+</span> d)<span style="color:#f92672">%</span><span style="color:#ae81ff">10</span>,(p2[<span style="color:#ae81ff">1</span>]<span style="color:#f92672">.</span>val <span style="color:#f92672">+</span> d)<span style="color:#f92672">//</span><span style="color:#ae81ff">10</span>)
                p1<span style="color:#f92672">.</span>next <span style="color:#f92672">=</span> ListNode(value)
                p1 <span style="color:#f92672">=</span> p1<span style="color:#f92672">.</span>next
                p2 <span style="color:#f92672">=</span> (p2[<span style="color:#ae81ff">0</span>],p2[<span style="color:#ae81ff">1</span>]<span style="color:#f92672">.</span>next)
                d <span style="color:#f92672">=</span> s
            <span style="color:#66d9ef">elif</span> p2[<span style="color:#ae81ff">0</span>]<span style="color:#f92672">!=</span><span style="color:#66d9ef">None</span> <span style="color:#f92672">and</span> p2[<span style="color:#ae81ff">1</span>]<span style="color:#f92672">==</span><span style="color:#66d9ef">None</span>:
                value, s <span style="color:#f92672">=</span> ((p2[<span style="color:#ae81ff">0</span>]<span style="color:#f92672">.</span>val <span style="color:#f92672">+</span> d)<span style="color:#f92672">%</span><span style="color:#ae81ff">10</span>,(p2[<span style="color:#ae81ff">0</span>]<span style="color:#f92672">.</span>val <span style="color:#f92672">+</span> d)<span style="color:#f92672">//</span><span style="color:#ae81ff">10</span>)
                p1<span style="color:#f92672">.</span>next <span style="color:#f92672">=</span> ListNode(value)
                p1 <span style="color:#f92672">=</span> p1<span style="color:#f92672">.</span>next
                p2 <span style="color:#f92672">=</span> (p2[<span style="color:#ae81ff">0</span>]<span style="color:#f92672">.</span>next,p2[<span style="color:#ae81ff">1</span>])
                d <span style="color:#f92672">=</span> s
            <span style="color:#66d9ef">elif</span> p2[<span style="color:#ae81ff">0</span>]<span style="color:#f92672">==</span><span style="color:#66d9ef">None</span> <span style="color:#f92672">and</span> p2[<span style="color:#ae81ff">1</span>]<span style="color:#f92672">==</span><span style="color:#66d9ef">None</span> <span style="color:#f92672">and</span> d<span style="color:#f92672">!=</span><span style="color:#ae81ff">0</span>:
                p1<span style="color:#f92672">.</span>next <span style="color:#f92672">=</span> ListNode(d)
                d<span style="color:#f92672">=</span><span style="color:#ae81ff">0</span>
            <span style="color:#66d9ef">elif</span> p2[<span style="color:#ae81ff">0</span>]<span style="color:#f92672">==</span><span style="color:#66d9ef">None</span> <span style="color:#f92672">and</span> p2[<span style="color:#ae81ff">1</span>]<span style="color:#f92672">==</span><span style="color:#66d9ef">None</span> <span style="color:#f92672">and</span> d<span style="color:#f92672">==</span><span style="color:#ae81ff">0</span>:
                <span style="color:#66d9ef">break</span>
        <span style="color:#66d9ef">return</span> head<span style="color:#f92672">.</span>next
</code></pre></div><p>In this example, p1 and p2 are pointers.</p></article>
    </section>

    

    
    <article class="ui segment utterances-comments" data-html2canvas-ignore>
      <script
        src="https://utteranc.es/client.js"
        repo="erwinLiYH/utterances_repo"
        issue-term="og:title"
        theme="github-light"
        crossorigin="anonymous"
        async>
      </script>
    </article>
    

    
  </div>
</div>


            <footer class="ui basic center aligned segment" style="background-color: transparent;">
              
              <p>© 2020 - 2022 LYH&#39;s Blog</p>
              

              <p>Powered by <a href="https://gohugo.io/" target="_blank">Hugo</a> with theme <a href="https://github.com/g1eny0ung/hugo-theme-dream" target="_blank">Dream</a>.</p>

              
            </footer>
          </div>
        </section>
        <section class="back">
          <div class="dream-max-width">
            <header class="ui basic very padded segment dream-header">
  <div class="ui small circular image">
    
    <img src="/img/ichigo_square.jpg" />
    
  </div>

  <div class="content">
    <h1 class="ui medium header">Li Yuanhao&#39;s Blog<div class="sub header">python yyds</div>
    </h1>

    <article class="ui horizontal list">
      
      <a class="item" href="/posts">
        <i class="archive icon" title="Archives"></i>
      </a>
      
      <a class="item" href="/categories">
        <i class="th list icon" title="All Categories"></i>
      </a>
      <a class="item" href="/tags">
        <i class="tags icon" title="All Tags"></i>
      </a>
    </article>

    
    <article class="dream-tags">
    
      
      
      <a class="ui label" href="/tags/arch/" title="Arch">Arch</a>
    
      
      
      <a class="ui label" href="/tags/blog/" title="Blog">Blog</a>
    
      
      
      <a class="ui label" href="/tags/hugo/" title="Hugo">Hugo</a>
    
      
      
      <a class="ui label" href="/tags/install/" title="Install">Install</a>
    
      
      
      <a class="ui label" href="/tags/instruction/" title="Instruction">Instruction</a>
    
      
      
      <a class="ui label" href="/tags/latex/" title="Latex">Latex</a>
    
      
      
      <a class="ui label" href="/tags/openmp/" title="Openmp">Openmp</a>
    
      
      
      <a class="ui label" href="/tags/pandas/" title="Pandas">Pandas</a>
    
      
      
      <a class="ui label" href="/tags/pyinstaller/" title="Pyinstaller">Pyinstaller</a>
    
      
      
      <a class="ui label" href="/tags/python/" title="Python">Python</a>
    
      
      
      <a class="ui label" href="/tags/stack/" title="Stack">Stack</a>
    
      
      
      <a class="ui label" href="/tags/tidyverse/" title="Tidyverse">Tidyverse</a>
    
    </article>
    
  </div>
</header>


<div class="ui relaxed grid dream-grid dream-back">
  
  
  
  <div class="sixteen wide mobile eight wide tablet four wide computer column dream-column">
    <article class="ui segment markdown-body">
      <h3 class="ui header">About Me</h3>
      <p>Education background:</p>
<ol>
<li>
<p>Bachelor:</p>
<p><strong>Data science</strong> in <a href="https://www.uic.edu.cn/">Peking Normal University-HongKong Baptist University United International University (UIC)</a></p>
</li>
<li>
<p>Msc:</p>
<p><strong>High performance computing with data science</strong> in <a href="https://www.ed.ac.uk/">University of Edinburgh</a></p>
</li>
</ol>
<p>Research area:</p>
<ol>
<li>NLP</li>
<li>CV</li>
<li>HPC</li>
</ol>
<p>Published papers:</p>
<ol>
<li>TBD</li>
</ol>
<p>Interesting:</p>
<ol>
<li>Guqin(古琴)</li>
<li>Classical music</li>
</ol>

    </article>
  </div>
  
  <div class="sixteen wide mobile eight wide tablet four wide computer column dream-column">
    <article class="ui segment markdown-body">
      <h3 class="ui header">个人简介</h3>
      <p>学习经历：</p>
<ol>
<li>
<p>学士</p>
<p>就读于<a href="https://www.uic.edu.cn/">北京师范大学-香港浸会大学联合国际学院 (UIC</a>)，专业为<strong>数据科学</strong></p>
</li>
<li>
<p>研究生</p>
<p>就读于<a href="https://www.ed.ac.uk/">爱丁堡大学</a>，专业为<strong>高性能运算与大数据</strong></p>
</li>
</ol>
<p>研究方向：</p>
<ol>
<li>NLP</li>
<li>CV</li>
<li>HPC</li>
</ol>
<p>发表论文：</p>
<ol>
<li>TBD</li>
</ol>
<p>兴趣爱好：</p>
<ol>
<li>古琴</li>
<li>古典音乐</li>
</ol>

    </article>
  </div>
  

  <div class="sixteen wide mobile eight wide tablet four wide computer column dream-column">
    <article class="ui segment">
      <h3 class="ui header">Social Links</h3>
      <nav class="ui secondary menu dream-menu dream-socials">
  

  
  <div class="item">
    <a href="mailto:erwinli@qq.com">
      <i class="large mail icon" title="Email"></i>
    </a>
  </div>
  

  

  

  

  

  

  
  <div class="item">
    <a href="https://github.com/ErwinLiYH" target="_blank">
      <i class="large github icon" title="GitHub"></i>
    </a>
  </div>
  

  

  
</nav>

    </article>
  </div>

  <div class="sixteen wide mobile eight wide tablet four wide computer column dream-column">
    
  </div>

  
  
</div>

          </div>
        </section>
      </div>
    </div>

    <script>
  window.defaultDark =  true 
  window.backgroundDark = "#b36d61"
  window.backgroundImageDark = "/img/1.jpg"
  window.darkNav =  null 
  window.hasTwitterEmbed =  null 

  if (window.hasTwitterEmbed) {
    
    window.twttr = (function (d, s, id) {
      var js,
        fjs = d.getElementsByTagName(s)[0],
        t = window.twttr || {}
      if (d.getElementById(id)) return t
      js = d.createElement(s)
      js.id = id
      js.src = 'https://platform.twitter.com/widgets.js'
      fjs.parentNode.insertBefore(js, fjs)

      t._e = []
      t.ready = function (f) {
        t._e.push(f)
      }

      return t
    })(document, 'script', 'twitter-wjs')
  }
</script>
<script src="/js/jquery.min.js"></script>
<script src="/js/semantic.min.js"></script>
<script src="/js/jquery.overlayScrollbars.min.js"></script>
<script src="/js/header.js"></script>
<script src="/js/main.js"></script>
<script src="/js/theme.js"></script>

    
<script src="/js/html2canvas.min.js"></script>
<script src="/js/post.js"></script>


<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.2.0/highlight.min.js"></script>



<script>
  hljs.initHighlightingOnLoad()
  setHighlightTheme()

  function setHighlightTheme() {
    var isDark = localStore.getItem('hugo-theme-dream-is-dark')
    isDark = isDark ? isDark : window.defaultDark ? 'y' : isDark

    var lightTheme = "github"
    var darkTheme = "dracula"
    var theme = isDark === 'y' ? darkTheme : lightTheme

    $('link[data-highlight]').attr('href', 'https://cdn.jsdelivr.net/gh/highlightjs/cdn-release/build/styles/' + theme + '.min.css')
    $('pre').css('background', isDark === 'y' ? '#333' : '')
  }
</script>





    
    <div class="ui inverted segment" id="dream-search">
  <div class="ui search">
    <div class="ui transparent input">
      <input class="prompt" type="text" placeholder="Search" />
    </div>
    <div class="results"></div>
  </div>
</div>
<script>
  $(document).ready(function () {
    $.getJSON('http:\/\/erwinliyh.github.io/index.json', function (data) {
      $('.ui.search').search({
        source: data,
        searchFields: ['title'],
        showNoResults: true,
      })
    })
  })
</script>
<script src="/js/search.js"></script>

    

    

    
  </body>
</html>
